﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace RgChannelBot
{
    public class ConnectionData
    {
        public ConnectionData(string name, string ipaddress, int port)
        {
            Name = name;
            IPAddress = ipaddress;
            Port = port;
        }

        public string Name { get; set; }
        public string IPAddress { get; set; }
        public int Port { get; set; }
        public bool Locked { get; set; }

        public async Task<string> SendMsg(string msg)
        {
            return await Task.Run(() =>
            {
                string response = "";
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 5000);
                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 5000);
                IPAddress ip = System.Net.IPAddress.TryParse(IPAddress, out ip) ? ip : Dns.GetHostEntry(IPAddress).AddressList[0];
                try
                {
                    socket.Connect(new IPEndPoint(ip, Port));
                    socket.Send(Encoding.UTF8.GetBytes(msg));
                    byte[] buffer = new byte[1024];
                    int count = socket.Receive(buffer);
                    response = Encoding.UTF8.GetString(buffer, 0, count);
                    socket.Close();
                }
                catch (SocketException)
                {
                    response = "Offline";
                    socket.Close();
                }
                return response;
            });
        }
    }
}